package com.ncmmall.application.util;

import com.feijin.commons.exceptions.InterfaceException;
import com.feijin.commons.lang.PropertiesHelps;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.StringEntity;

/**
 * 微信订阅消息发送
 *
 * @author linxs
 * @date 2020-05-11 18:06
 */
public class WechatMessageUtils {

    /**
     * 发送微信订阅消息
     */
    public static void send(String userOpenId, String templateId, String data) {

        try {

            String result = HttpRequests.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + PropertiesHelps.getValue("wx.appid") + "&secret=" + PropertiesHelps.getValue("wx.appSecret"));
            JSONObject jsonObject = JSONObject.fromObject(result);

            if (jsonObject.get("errcode") == null || (int) jsonObject.get("errcode") == 0) {
                String accessToken = (String) jsonObject.get("access_token");

                JSONObject body = new JSONObject();
                body.put("access_token", accessToken);
                body.put("touser", userOpenId);
                body.put("template_id", templateId);
                body.put("data", data);

                HttpResponse response = Request.Post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken)
                        .body(new StringEntity(body.toString(), "utf-8"))
                        .execute()
                        .returnResponse();

                if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                    throw new InterfaceException("[接口非200响应码]");
                }
            }
        } catch (Exception e) {
            //do nothing
        }
    }


}
